package com.zwz.eduservice.controller.front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zwz.commonutils.JwtUtils;
import com.zwz.commonutils.R;
import com.zwz.eduservice.client.OrderClient;
import com.zwz.eduservice.entity.EduCourse;
import com.zwz.eduservice.entity.chapter.ChapterVo;
import com.zwz.eduservice.entity.front.CourseFrontVo;
import com.zwz.eduservice.entity.front.CourseWebVo;
import com.zwz.eduservice.entity.vo.CourseInfoVo;
import com.zwz.eduservice.service.EduChapterService;
import com.zwz.eduservice.service.EduCourseService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/coursefront")
//@CrossOrigin
public class CourseFrontController {

    @Autowired
    private EduCourseService courseService;

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private OrderClient orderClient;

    @ApiOperation(value = "带条件分页查询课程")
    @PostMapping("getCourseFrontList/{page}/{limit}")
    public R getCourseFrontList(@PathVariable Long page, @PathVariable Long limit,
                                @RequestBody(required = false) CourseFrontVo courseFrontVo){
        Page<EduCourse> pageParam = new Page<>(page, limit);
        Map<String, Object> map = courseService.getCourseFrontList(pageParam,courseFrontVo);
        return  R.ok().data(map);
    }

    @ApiOperation(value = "查询课程详情")
    @GetMapping("getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request){
        //编写sql，查询课程信息
        CourseWebVo courseWebVo = courseService.getBaseCourseInfo(courseId);
        //查询章节和小节
        List<ChapterVo> chapterVideoList = chapterService.getChapterVideoByCourseId(courseId);

        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (memberId == ""){
            return R.ok().data("courseWebVo",courseWebVo).data("chapterVideoList",chapterVideoList);
        }else {
            //查询课程是否购买
            boolean buyCourse = orderClient.isBuyCourse(courseId,memberId);
            return R.ok().data("courseWebVo",courseWebVo).data("chapterVideoList",chapterVideoList).data("isBuy",buyCourse);
        }
    }

    @ApiOperation(value = "根据课程id查询课程详情")
    @GetMapping("getCourseInfoById/{courseId}")
    public CourseInfoVo getCourseInfoById(@PathVariable String courseId){
        //编写sql，查询课程信息
        CourseWebVo courseWebVo = courseService.getBaseCourseInfo(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(courseWebVo,courseInfoVo);
        return courseInfoVo;
    }
}
